package com.leon.android.common.proxy

import android.content.SharedPreferences
import com.leon.android.common.extensions.toJson
import com.leon.android.common.extensions.toObject
import java.lang.reflect.Type
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * 属性代理类，可以实时更新sp文件中对应的内容，屏蔽冗长的sp操作
 * */
class SpProperty<T>(
    val spKey: String,
    val type:Type,
    val spFile: SharedPreferences = sharedPreferences
) : ReadWriteProperty<Any, T?> {

    private var value: T? = null


    override fun getValue(thisRef: Any, property: KProperty<*>): T? {
        if (value == null) {
            value = spFile.getString(spKey, "")?.toObject(type)
        }
        return value
    }

    override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) {
        spFile.edit().putString(spKey, value.toJson()).apply()
        this.value = value
    }

    companion object {
        lateinit var sharedPreferences: SharedPreferences
        fun init(sharedPreferences: SharedPreferences) {
            this.sharedPreferences = sharedPreferences
        }
    }
}